package com.xjrsoft.module.demo.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.xjrsoft.module.demo.entity.Multi;
import com.xjrsoft.module.demo.entity.MultiChild;
import com.xjrsoft.module.demo.mapper.MultiChildMapper;
import com.xjrsoft.module.demo.mapper.MultiMapper;
import com.xjrsoft.module.demo.service.IMultiService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @title: DemoServiceImpl
 * @Author tzx
 * @Date: 2022/4/16 23:28
 * @Version 1.0
 */
@Service
@AllArgsConstructor
public class MultiServiceImpl extends MPJBaseServiceImpl<MultiMapper, Multi> implements IMultiService {

    private final MultiMapper multiMapper;

    private final MultiChildMapper multiChildMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(Multi multi) {
        multiMapper.insert(multi);
        for (MultiChild multiChild : multi.getChildList()) {
            multiChildMapper.insert(multiChild);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(Multi multi) {
        multiMapper.updateById(multi);
        multiChildMapper.deleteBatchIds(multi.getChildList().stream().map(MultiChild::getId).collect(Collectors.toList()));
        for (MultiChild multiChild : multi.getChildList()) {
            multiChildMapper.insert(multiChild);
        }
        return true;
    }

    @Override
    public Boolean delete(List<Long> ids) {
        multiMapper.deleteBatchIds(ids);
        multiChildMapper.delete(Wrappers.lambdaQuery(MultiChild.class).in(MultiChild::getParentId, ids));
        return true;
    }
}
